package api

import (
	"Walker/app/http/controller/admin"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"reflect"
)

type Reflect struct {
	Inter admin.Tang
}

type STang struct {
}

func (test *STang) Eat() string {
	return "我正在吃饭"
}

func (controller *Reflect) Index(ctx *gin.Context) {
	provider := func(string2 string) admin.Tang {
		return &STang{}
	}

	var (
		argValue = reflect.ValueOf(provider)
		argType  = reflect.TypeOf(provider)
	)

	if argValue.Kind() != reflect.Func {
		panic(errors.New("参数必须是函数"))
	}

	var (
		arguments    = make([]reflect.Type, 0)
		returns      = make([]reflect.Type, 0)
		argumentsLen = argType.NumIn()
		returnsLen   = argType.NumOut()
	)

	for argIndex := 0; argIndex < argumentsLen; argIndex++ {
		arguments = append(arguments, argType.In(argIndex))
	}

	for outIndex := 0; outIndex < returnsLen; outIndex++ {
		returns = append(returns, argType.Out(outIndex))
	}
	if returns[0].Kind() == reflect.Ptr {
		fmt.Println("这是一个指针")
		returns[0] = returns[0].Elem()
	}

	pkgPath := returns[0].PkgPath()
	str := IfString(pkgPath == "", "", pkgPath+".") + returns[0].Name()
	ss, ok := reflect.New(reflect.TypeOf(STang{})).Interface().(admin.Tang)
	if !ok {
		fmt.Println("错误的")
	}
	fmt.Println(str, ss.Eat())
	//fmt.Println(arguments, returns, argumentsLen, returnsLen, argValue, pkgPath, str, ss)
}
func IfString(condition bool, str1 string, otherStr ...string) string {
	if condition {
		return str1
	}
	return StringOr(otherStr...)
}

// StringOr 尽量不返回空字符串
func StringOr(otherStr ...string) string {
	for _, str := range otherStr {
		if str != "" {
			return str
		}
	}
	return ""
}
func (controller *Reflect) Test(ctx *gin.Context) {
	fmt.Println(controller.Inter.Eat())
}
